<template>
  <div class="app-list-page">
    <div class="page-center">
      <a-page-header
        title="账号设置"
        @back="() => $router.back()"
        style="padding-left: 10px; padding-top: 0"
      >
      </a-page-header>
      <a-card :bordered="false" style="width: 100%; border-radius: 6px">
        <a-form :model="formRef" layout="vertical" style="width: 400px">
          <a-form-item label="昵称" v-bind="validateInfos.nickname">
            <a-input v-model:value="formRef.nickname" placeholder="请输入" />
          </a-form-item>
          <a-form-item label="头像" v-bind="validateInfos.avatar">
            <a-upload
              :action="$utils.imgAction"
              :headers="{ 'org-token': $store.getters.token }"
              v-model:file-list="fileList"
              @change="handleUploadChange"
              :multiple="true"
              name="image"
              :data="{ dir: 'work_ai' }"
              accept="image/*"
              list-type="picture-card"
            >
              <div v-if="!fileList.length">
                <PlusOutlined />
                <div>上传图片</div>
              </div>
            </a-upload>
          </a-form-item>
          <a-row style="margin-bottom: 20px">
            <a-col>手机号：</a-col>
            <a-col>
              <a-space>
                <span>{{ isPhone ? userInfo.phone : "未绑定手机号" }}</span>
                <span v-if="!isPhone">
                  <a @click="bindPhone">绑定手机号</a>
                </span>
              </a-space>
            </a-col>
          </a-row>
        </a-form>
        <a-button type="primary" @click="onSubmit" style="margin-top: 20px"
          >保存</a-button
        >
      </a-card>
    </div>

    <LoginModal
      :visible="loginVisible"
      @onClose="loginVisible = false"
      @loginCallback="loginCallback"
    />
  </div>

  <BindPhone
    :visible="bindPhoneVisible"
    @onClose="onCloseBindPhone"
    @loginCallback="bindPhoneCallback"
  />
</template>

<script>
import {
  ref,
  defineComponent,
  reactive,
  toRefs,
  computed,
  watch,
  toRaw,
  h,
  onBeforeUnmount,
  createVNode,
  inject,
} from "vue";
import request from "../../common/utils/request";
import store from "../../store/index";
import { useRoute, useRouter } from "vue-router";
import utils from "../../common/utils/utils";
import { Form, Modal, notification, message } from "ant-design-vue";
import { PlusOutlined } from "@ant-design/icons-vue";
import BindPhone from "../../components/BindPhone/index.vue";

const useForm = Form.useForm;
export default defineComponent({
  name: "userSetting",
  components: {
    PlusOutlined,
    BindPhone,
  },

  setup() {
    const route = useRoute();
    const router = useRouter();

    const state = reactive({
      loginVisible: false,
      fileList: [],
      isPhone: false,
      userInfo: {},
      bindPhoneVisible: false,
    });

    const formRef = reactive({
      nickname: "",
      avatar: "",
    });

    const rulesRef = reactive({
      nickname: [{ required: true, message: "昵称不能为空" }],
    });

    const { resetFields, validate, validateInfos } = useForm(formRef, rulesRef);

    const getDetail = () => {
      state.fileList = [];
      resetFields();
      store.dispatch("GetUserInfo").then((res) => {
        console.log("GetUserInfo", res);
        if (res && res.id) {
          formRef.nickname = res.nickname;

          if (res.avatar) {
            state.fileList.push({
              uid: 1,
              name: res.avatar,
              status: "done",
              url: res.avatar,
            });
            formRef.avatar = res.avatar;
          }
        }
      });
      console.log();
    };

    const init = () => {
      getDetail();
      utils.getUserInfo().then((userInfo) => {
        state.userInfo = userInfo;
        state.isPhone = utils.validatePhoneNumber(userInfo.phone);
      });
    };

    utils.checkLogin().then((isLogin) => {
      if (!isLogin) {
        state.loginVisible = true;
        return;
      }
      init();
    });

    const loginCallback = () => {
      state.loginVisible = false;
      router.go(0);
    };

    // 上传图片
    const handleUploadChange = (info) => {
      let resFileList = [...info.fileList];
      if (resFileList.length) {
        resFileList.map((file, index) => {
          if (file.response) {
            if (file.response.code == 1000) {
              file.url = file.response.data.fileUrl;
            } else {
              message.warning(file.response.msg);
              resFileList.splice(index, 1);
            }
          }
        });
      }
      state.fileList = resFileList;
      if (state.fileList.length) {
        formRef.avatar = state.fileList[0].url;
      } else {
        formRef.avatar = "";
      }
    };

    const onSubmit = () => {
      validate().then(() => {
        let params = {};
        for (let key in formRef) {
          params[key] = formRef[key];
        }
        request
          .put("/work_ai", "/user/info", {
            ...params,
          })
          .then((res) => {
            store.dispatch("SetUserInfo", null).then(() => {
              message.success("保存成功");
            });
          });
      });
    };

    const bindPhone = () => {
      state.bindPhoneVisible = true;
    };

    const bindPhoneCallback = () => {
      state.bindPhoneVisible = false;
    };

    return {
      ...toRefs(state),
      loginCallback,
      handleUploadChange,
      validateInfos,
      formRef,
      onSubmit,
      bindPhoneCallback,
      bindPhone,
    };
  },
});
</script>

<style lang="less" scoped>
.app-list-page {
  width: 100%;
  height: 100%;
  padding: 20px;
  overflow: hidden auto;

  .page-center {
    margin: 0 auto;
    max-width: 1200px;

    .app-list-wrap {
      .app-list {
        padding: 20px 0 40px 20px;
        .app-item {
          height: 140px;
          padding: 15px 20px;
          background-color: #fff;
          border-radius: 12px;
          margin-right: 20px;
          margin-bottom: 20px;
          cursor: pointer;
          transition: 0.2s ease;
          box-shadow: 0 0px 10px #193e7b14;
          position: relative;

          &:hover {
            -webkit-transform: translateY(-3px);
            -ms-transform: translateY(-3px);
            transform: translateY(-3px);
            -webkit-transition: all 0.5s ease-out;
            transition: all 0.5s ease-out;
            background-color: #f3f0ff;

            .close-button {
              display: block;
            }
          }

          .app-item-logo {
            width: 48px;
            height: 48px;
            object-fit: cover;
            margin-right: 20px;
          }

          .app-item-name {
            font-size: 20px;
          }

          .app-item-intro {
            margin-top: 10px;
            color: #666;
            font-size: 16px;
            overflow: hidden;
            text-overflow: ellipsis;
            display: -webkit-box;
            -webkit-line-clamp: 2;
            -webkit-box-orient: vertical;
          }

          .close-button {
            position: absolute;
            top: -5px;
            right: -5px;
            font-size: 18px;
            color: #666;
            display: none;
            -webkit-transition: all 0.5s ease-out;
            transition: all 0.5s ease-out;
          }
        }
      }

      .pagination-wrap {
        display: flex;
        justify-content: flex-end;
        align-items: center;
        padding-right: 20px;
      }
    }

    .empty-wrap {
      width: 100%;
      display: flex;
      justify-content: center;
      padding-top: 150px;
    }
  }

  .ant-page-header-content {
    padding-top: 0px;
  }
}
</style>
